import numpy as np
from numba import njit


def main():
    # 使用自定义矩阵乘法
    p1 = p2 = np.asarray([
        [10, 10, 5, 5],
        [10, 8, 5, 5],
        [10, 15, 6, 6],
        [10, 20, 7, 7]
    ], dtype=np.float32)
    inters = rects_inter_area(p1, p2)
    print("使用 Numba 的自定义矩阵乘法结果：\n", inters)


@njit
def rects_inter_area(p1: np.ndarray, p2: np.ndarray) -> np.ndarray:

    assert p1.shape[1] == p2.shape[1] == 4, "要求点列使用 (x, y, w, h) 格式"

    # 创建结果矩阵
    inters = np.zeros((p1.shape[0], p2.shape[0]), dtype=np.float32)

    # 自定义矩阵乘法逻辑
    # min(max(0, (wi+wj)/2-abs(xi-xj)), wi, wj) * min(max(0, (hi+hj)/2-abs(yi-yj)), hi, hj)
    for i in range(p1.shape[0]):
        for j in range(p2.shape[0]):
            # 好惨啊，python 写这么多就行，翻译成 cpp 要写辣么多
            # w = (p1[2] + p2[2]) / 2 - abs(p1[0] - p2[0])
            # h = (p1[3] + p2[3]) / 2 - abs(p1[1] - p2[1])
            # inters[i, j] = min(p1[2], p2[2], max(0, w)) * min(p1[3], p2[3], max(0, h))

            w = (p1[i, 2] + p2[j, 2]) / 2 - np.abs(p1[i, 0] - p2[j, 0])
            h = (p1[i, 3] + p2[j, 3]) / 2 - np.abs(p1[i, 1] - p2[j, 1])
            inters[i, j] = np.minimum(np.minimum(p1[i, 2], p2[j, 2]), np.maximum(0, w)) * np.minimum(np.minimum(p1[i, 3], p2[j, 3]), np.maximum(0, h))

            # 愚蠢的 cpp 的愚蠢错误
            # dx: float = p1[0] - p2[0]
            # dx: float = dx if dx >= 0. else -dx
            # w: float = (p1[2] + p2[2]) / 2. - dx
            #
            # dy: float = p1[1] - p2[1]
            # dy: float = dy if dy >= 0. else -dy
            # h: float = (p1[3] + p2[3]) / 2. - dy
            #
            # w: float = w if w > 0. else 0.
            # w: float = w if w < p1[2] else p1[2]
            # w: float = w if w < p2[2] else p2[2]
            #
            # h: float = h if h > 0. else 0.
            # h: float = h if h < p1[3] else p1[3]
            # h: float = h if h < p2[3] else p2[3]

            # inters[i, j] = w * h

    return inters


main()
